package com.cyzy.config;

import com.alibaba.fastjson.JSON;
import com.cyzy.pojo.ChatMessage;
import com.cyzy.pojo.Coordinates;
import com.cyzy.pojo.Netizen;
import com.cyzy.service.MessageService;
import com.cyzy.utils.MessageUtils;
import com.cyzy.utils.SpringContextUtils;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author cuncun
 * @create 2025-06-05 下午2:37
 */
@ServerEndpoint(value = "/realTime",configurator = GetHttpSessionConfiguratorS.class)
@Component
public class RealTimeLocation {

    //存储通信的用户
    private static final Map<String, Session> onlineUsers = new ConcurrentHashMap<>();

    //建立websocket连接后，被调用
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) throws IOException {
        System.out.println("WebSocket 连接建立");

        String userId = (String)config.getUserProperties().get("userId");

        if (userId == null ) {
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "认证失败"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        System.out.println("用户登录成功: " + userId );

        // 把 session 存入 map，用于后续消息推送
        onlineUsers.put(userId, session);
    }

    //    浏览器发送消息到服务端，该方法被调用
    @OnMessage
    public void onMessage(Session session,String message){
        try{
            System.out.println(message + " message");
            Coordinates msg = JSON.parseObject(message, Coordinates.class);
            String senderId = (String) session.getUserProperties().get("userId");//发送方的id
            long id = msg.getId();//接收方的id
            long  x = msg.getCoordinatesX(); // 发送方的x坐标
            long y = msg.getCoordinatesX(); // 发送方的y坐标
            String style = msg.getStyle();// 发送方的类型
            // 构造消息
            String formattedMessage = MessageUtils.getMessage(false, senderId, msg);
            //创建接收方的id
            String toUserId = style + id;
            // 发送给目标用户
            Session receiverSession = onlineUsers.get(toUserId);
            if (receiverSession != null && receiverSession.isOpen()) {
                receiverSession.getBasicRemote().sendText(formattedMessage);
            } else {
                System.out.println("目标用户不在线: " + toUserId);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //断开websocket连接时被调用
    @OnClose
    public void OnClose(Session session){
        String userId = (String) session.getUserProperties().get("userId");
        if (userId != null) {
            onlineUsers.remove(userId);
            System.out.println("用户下线: " + userId);
        }
    }

    // 出现错误时调用
    @OnError
    public void onError(Throwable throwable) {
        System.err.println("WebSocket 出现错误: " + throwable.getMessage());
        throwable.printStackTrace();
    }
}
